﻿using Home.Domain.Entities;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Utilities.Validation;
using Omu.ValueInjecter;
using Utilities.ViewModel;
using System.Data;
using System.Globalization;

namespace Home.WebUI.Areas.Mythi.Controllers
{
    [Home.WebUI.Areas.NewAdmin.Models.AdminLogin]
    public class LeiBieController : Controller
    {
        //
        // GET: /Mythi/LeiBie/

        #region 基本
        private EFDbContext db = new EFDbContext();
        private DbSet<LeiBie> MEntity
        {
            get { return db.LeiBies; }
        }
        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
        #endregion

        public ActionResult Index()
        {
            var model = MEntity.OrderBy(c => c.Sort).ToList();
            return View(model);
        }

        #region 增
        public ActionResult Create()
        {
            var model = new LeiBieCreate();
            return View(model);
        }
        [HttpPost]
        public ActionResult Create(LeiBieCreate model)
        {
            //try
            //{
            if (model.UniValidate.CheckAll(Request))
            {
                var content = new LeiBie();
                content.InjectFrom(model);
                int sort = MEntity.Select(p => p.Sort).DefaultIfEmpty(0).Max();
                content.Sort = sort + 1;
                MEntity.Add(content);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            //}
            //catch (DataException)
            //{
            //    TempData["Tip"] = new TipModel(0, "无法保存更改。再试一次，和如果问题仍然存在，请联系您的系统管理员");
            //}
            return View(model);
        }
        #endregion

        #region 改
        public ActionResult Edit(int id)
        {
            var model = new LeiBieEdit();
            model.InjectFrom(MEntity.Find(id));
            return View(model);
        }
        [HttpPost]
        public ActionResult Edit(LeiBieEdit model)
        {
            try
            {
                if (model.UniValidate.CheckAll(Request))
                {
                    var content = new LeiBie { Id = model.Id };
                    MEntity.Attach(content);
                    content.InjectFrom(model);
                    db.SaveChanges();
                    TempData["Tip"] = new TipModel(1, "保存成功");
                    return RedirectToAction("Edit", new { id = model.Id });
                }
            }
            catch (DataException)
            {
                TempData["Tip"] = new TipModel(0, "无法保存更改。再试一次，和如果问题仍然存在，请联系您的系统管理员");
            }
            return View(model);
        }
        #endregion

        #region 删
        [HttpPost]
        public ActionResult Delete(int id)
        {
            try
            {
                // TODO: Add delete logic here    
                if (Request.IsAjaxRequest())
                {
                    var content = MEntity.Find(id);
                    //int newsNumer = MEntity.Count(n => n.PNewsId == content.Id);
                    //int newsNumer = content.News.Count();
                    var SubNumber = content.Successes.Count;
                    if (SubNumber > 0)
                    {
                        return Content(SubNumber.ToString(CultureInfo.InvariantCulture));
                    }
                    MEntity.Remove(content);
                    //EntityState stateafter = db.Entry(content).State;//Deleted状态     
                    int result = db.SaveChanges();
                    return Content("0");
                }
                else
                {
                    return Content("-1");
                }
            }
            catch
            {
                return Content("-1");
            }
        }
        #endregion

        #region 移
        //[HttpPost]
        public ActionResult Up(int id)
        {
            LeiBie content = MEntity.Find(id);
            LeiBie contentup = MEntity.Where(c => c.Sort < content.Sort).OrderByDescending(c => c.Sort).FirstOrDefault();
            if (contentup == null)
            {
                return Redirect(Request.UrlReferrer.ToString());
            }
            MEntity.Attach(content);
            content.Sort = contentup.Sort;
            MEntity.Attach(contentup);
            contentup.Sort = contentup.Sort + 1;
            db.SaveChanges();
            return Redirect(Request.UrlReferrer.ToString());
        }
        #endregion

        //验证是否存在此标题
        [HttpPost]
        public ActionResult TitleExists(string value, int id = 0)//id为排除的值，0无排除
        {
            Func<LeiBie, bool> where;
            if (id == 0)
            {
                where = c => c.Title == value;
            }
            else
            {
                where = c => c.Title == value && c.Id != id;
            }
            bool exists = true;
            int number = MEntity.Where(where).Count();//此处传递委托不好生成的sql语句先执行后过滤的。
            if (number == 0)
            {
                exists = false;
            }
            var valJson = new { verify = !exists };
            return Json(valJson, JsonRequestBehavior.AllowGet);
        }

    }
    #region 验证
    public class LeiBieCreate
    {
        public int Id { get; set; }
        public string Title { get; set; }

        public UniValidate UniValidate
        {
            get
            {
                var uv = new UniValidate();
                uv.InitName(() => Title).NotEmpty("标题不能为空").MaxLength(36).MyRemote(new { url = "/Mythi/LeiBie/TitleExists" }, "标题已存在");
                uv.ValidEnd(".form-horizontal");
                return uv;
            }
        }
    }
    public class LeiBieEdit
    {
        public int Id { get; set; }
        public string Title { get; set; }

        public UniValidate UniValidate
        {
            get
            {
                var uv = new UniValidate();
                uv.InitName(() => Title).NotEmpty("标题不能为空").MaxLength(36).MyRemote(new { url = "/Mythi/LeiBie/TitleExists?id=" + Id }, "标题已存在");
                uv.ValidEnd(".form-horizontal");
                return uv;
            }
        }
    }
    #endregion
}
